package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import one.stand.code.RedisCode;
import one.stand.entity.DynamicPosterEntity;
import one.stand.entity.ImageEntity;
import one.stand.entity.PosterEntity;
import one.stand.enums.LoginEnum;
import one.stand.model.*;
import one.stand.request.BusinessCardRequest;
import one.stand.request.CompanyAccountRequest;
import one.stand.request.DynamicRequest;
import one.stand.request.ShareRecordRequest;
import one.stand.service.CompanyAccontService;
import one.stand.service.PosterService;
import one.stand.service.WxSunCodeService;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: QIK
 * @CreateDate: 2019/6/26 9:15
 */
@Service
@Transactional
public class PosterServiceImpl extends PublicBaseService implements PosterService {
    @Autowired
    protected CompanyAccontService companyAccontService;

    @Autowired
    protected WxSunCodeService wxSunCodeService;

    @Override
    public ResultModel getCardPoster(BusinessCardRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail("卡片请求为空");
        }
        List<String> list = redisUtil.get(RedisCode.getCardPoster(request.getCardId()));
        if (list != null && list.size() > 0) {
            return ResultModel.success(list);
        }
        list = new ArrayList<>();

        BusinessCardModel model = businessCardMapper.select(new BusinessCardModel() {{
            setCardId(request.getCardId());
            setThumbsUserId(request.getId().intValue());
            setState(1);
        }});
        if (null == model) {
            log.info("未获取到名片信息");
            return ResultModel.fail(String.format("未获取到名片信息(cardId=%s,thumbsUserId=%s)", request.getCardId(), request.getId()));
        }
        if (StringUtils.isBlank(model.getWxTwoCode())) {
            String wxTwoCode = getWxCode(request.getCardId().toString(), model.getCompanyId().toString());
            if (StringUtils.isBlank(wxTwoCode)) {
                return ResultModel.fail(String.format("获取太阳码为空(cardId=%s,companyId=%s)", request.getCardId(), request.getCompanyId()));
            }
            model.setWxTwoCode(wxTwoCode);
        }
        CompanyAccountModel companyAccountModel = companyAccontService.selectByCompanyKey(new CompanyAccountRequest() {{
            setCompanyKey(request.getCompanyKey());
            setAccountType(LoginEnum.CRM.getAccountType());
        }});
        //list.add(card1(model,companyAccountModel.getAppName()));
        list.add(this.card2(model, companyAccountModel.getAppName()));
        list.add(this.card3(model, companyAccountModel.getAppName()));
        list.add(this.card4(model));
        list.add(this.card5(model));
        //新增海报
        list.add(this.card6(model));
        list.add(this.card7(model));
        list.add(this.card8(model));
        log.info("getCardPoster:",list);
        return ResultModel.success(list);
    }

    public void addCardList(String url, Integer cardId) {
        List<String> list = redisUtil.get(RedisCode.getCardPoster(cardId));
        if (null == list || list.size() <= 0) {
            list = new ArrayList<>();
        }
        list.add(url);
        redisUtil.set(RedisCode.getCardPoster(cardId), list);
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card1(BusinessCardModel model, String appName) {
        PosterEntity posterEntity = new PosterEntity();
        posterEntity.setImagePath(cardPosterConfig.getUrl1());
        posterEntity.setCompanyName(getObjectString(model.getCompanyName()));
        posterEntity.setEmail(getObjectString(model.getEmail()));
        posterEntity.setPhone(getObjectString(model.getPhone()));
        posterEntity.setCardName(getObjectString(model.getName()));
        posterEntity.setQRCodeUrl(getObjectString(model.getWxTwoCode()));
        posterEntity.setCardLogoUrl(getObjectString(model.getLogo()));
        posterEntity.setAppName(appName);
        InputStream inputStream = imageGenerateUtil.businessCardDraw1(posterEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card2(BusinessCardModel model, String appName) {
        PosterEntity posterEntity = new PosterEntity();
        posterEntity.setCardName(getObjectString(model.getName()));
        posterEntity.setPosition(getObjectString(model.getPosition()));
        posterEntity.setPhone(getObjectString(model.getPhone()));
        posterEntity.setQRCodeUrl(getObjectString(model.getWxTwoCode()));
        posterEntity.setCardLogoUrl(StringUtils.isBlank(model.getLogo()) ? cardPosterConfig.getCardLogoDefaultUrl() : model.getLogo());
        posterEntity.setCompanyLogo(getObjectString(model.getCompanyLogo()));
        posterEntity.setAppName(appName);
        posterEntity.setImagePath(cardPosterConfig.getUrl2());
        posterEntity.setCard2BackUrl(cardPosterConfig.getUrl2back());
        InputStream inputStream = imageGenerateUtil.businessCardDraw2(posterEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card3(BusinessCardModel model, String appName) {
        PosterEntity posterEntity = new PosterEntity();
        posterEntity.setQRCodeUrl(getObjectString(model.getWxTwoCode()));
        posterEntity.setCardLogoUrl(StringUtils.isBlank(model.getLogo()) ? cardPosterConfig.getCardLogoDefaultUrl() : model.getLogo());
        posterEntity.setCardName(getObjectString(model.getName()));
        posterEntity.setEmail(getObjectString(model.getEmail()));
        posterEntity.setImagePath(cardPosterConfig.getUrl3());
        posterEntity.setPhone(getObjectString(model.getPhone()));
        posterEntity.setAppName(appName);
        InputStream inputStream = imageGenerateUtil.businessCardDraw3(posterEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card4(BusinessCardModel model) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getUrl4());
        List<ImageEntity> list = new ArrayList<>();
        ImageEntity i = new ImageEntity();
        i.setType(1);
        i.setParam(model.getCompanyName());
        i.setSize(36);
        i.setColor(new Color(56, 56, 56));
        i.setCentered(true);
        i.setYAxis(936 + 34);
        i.setPlain(Font.BOLD);
        list.add(i);

        ImageEntity i2 = new ImageEntity();
        i2.setParam(model.getName());
        i2.setType(1);
        i2.setSize(36);
        i2.setColor(new Color(56, 56, 56));
        i2.setXAxis(81);
        i2.setYAxis(1060 + 34);
        i2.setPlain(Font.BOLD);
        list.add(i2);

        ImageEntity i3 = new ImageEntity();
        i3.setParam(model.getPosition());
        i3.setType(1);
        i3.setSize(28);
        i3.setColor(new Color(120, 120, 120));
        i3.setXAxis(81);
        i3.setYAxis(1114 + 26);
        i3.setPlain(Font.PLAIN);
        list.add(i3);

        ImageEntity i4 = new ImageEntity();
        i4.setParam(model.getPhone());
        i4.setType(1);
        i4.setSize(24);
        i4.setColor(new Color(168, 168, 168));
        i4.setXAxis(134);
        i4.setYAxis(1177 + 19);
        i4.setPlain(Font.PLAIN);
        list.add(i4);

        ImageEntity i5 = new ImageEntity();
        i5.setParam(model.getLogo());
        i5.setType(2);
        i5.setWidth(120);
        i5.setHigh(120);
        i5.setXAxis(157);
        i5.setYAxis(404);
        list.add(i5);

        ImageEntity i6 = new ImageEntity();
        i6.setParam(model.getWxTwoCode());
        i6.setType(2);
        i6.setWidth(120);
        i6.setHigh(120);
        i6.setXAxis(555);
        i6.setYAxis(1068);
        list.add(i6);
        imageEntity.setImageEntityList(list);
        InputStream inputStream = imageGenerateUtil.image(imageEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card5(BusinessCardModel model) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getUrl5());
        List<ImageEntity> list = new ArrayList<>();
        ImageEntity i = new ImageEntity();
        i.setParam(model.getLogo());
        i.setType(2);
        i.setWidth(120);
        i.setHigh(120);
        i.setXAxis(40);
        i.setYAxis(983);
        list.add(i);

        ImageEntity i2 = new ImageEntity();
        i2.setParam(model.getName());
        i2.setType(1);
        i2.setSize(36);
        i2.setColor(new Color(56, 56, 56));
        i2.setXAxis(48);
        i2.setYAxis(1128 + 34);
        i2.setPlain(Font.BOLD);
        list.add(i2);

        ImageEntity i3 = new ImageEntity();
        i3.setParam(model.getPhone());
        i3.setType(1);
        i3.setSize(24);
        i3.setColor(new Color(120, 120, 120));
        i3.setXAxis(48);
        i3.setYAxis(1191 + 19);
        i3.setPlain(Font.PLAIN);
        list.add(i3);

        ImageEntity i4 = new ImageEntity();
        i4.setParam(model.getEmail());
        i4.setType(1);
        i4.setSize(24);
        i4.setColor(new Color(120, 120, 120));
        i4.setXAxis(48);
        i4.setYAxis(1226 + 23);
        i4.setPlain(Font.PLAIN);
        list.add(i4);

        ImageEntity i5 = new ImageEntity();
        i5.setParam(model.getWxTwoCode());
        i5.setType(2);
        i5.setWidth(184);
        i5.setHigh(184);
        i5.setXAxis(522);
        i5.setYAxis(1083);
        list.add(i5);
        imageEntity.setImageEntityList(list);
        InputStream inputStream = imageGenerateUtil.image(imageEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card6(BusinessCardModel model) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getUrl6());
        List<ImageEntity> list = new ArrayList<>();
        ImageEntity i = new ImageEntity();
        i.setParam(model.getLogo());
        i.setType(2);
        i.setHeader(2);
        i.setWidth(97);
        i.setHigh(97);
        i.setXAxis(404);
        i.setYAxis(158);
        list.add(i);

        ImageEntity i2 = new ImageEntity();
        i2.setParam(model.getName());
        i2.setType(1);
        i2.setSize(40);
        i2.setColor(new Color(233,218,191));
        i2.setXAxis(401);
        i2.setYAxis(326);
        i2.setPlain(Font.BOLD);
        list.add(i2);

        ImageEntity i3 = new ImageEntity();
        i3.setParam(model.getPhone());
        i3.setType(1);
        i3.setSize(24);
        i3.setColor(new Color(233,218,191));
        i3.setXAxis(442);
        i3.setYAxis(420);
        i3.setPlain(Font.PLAIN);
        list.add(i3);

        ImageEntity i4 = new ImageEntity();
        i4.setParam(model.getEmail());
        i4.setType(1);
        i4.setSize(24);
        i4.setColor(new Color(233,218,191));
        i4.setXAxis(448);
        i4.setYAxis(456);
        i4.setPlain(Font.PLAIN);
        list.add(i4);

        ImageEntity i5 = new ImageEntity();
        i5.setParam(model.getWxTwoCode());
        i5.setType(2);
        i5.setWidth(401);
        i5.setHigh(401);
        i5.setXAxis(159);
        i5.setYAxis(636);
        list.add(i5);

        ImageEntity com = new ImageEntity();
        com.setParam(model.getCompanyName());
        com.setType(1);
        com.setSize(24);
        com.setColor(new Color(233,218,191));
        com.setXAxis(59);
        com.setYAxis(156);
        list.add(com);

        if(!StringUtils.isEmpty(model.getPosition())){
            ImageEntity post = new ImageEntity();
            post.setParam(model.getPosition());
            post.setType(1);
            post.setSize(24);
            post.setColor(new Color(233,218,191));
            post.setXAxis(400);
            post.setYAxis(363);
            list.add(post);
        }

        imageEntity.setImageEntityList(list);
        InputStream inputStream = imageGenerateUtil.image(imageEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        log.info("url------->:{}",url);
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card7(BusinessCardModel model) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getUrl7());
        List<ImageEntity> list = new ArrayList<>();
        ImageEntity i = new ImageEntity();
        i.setParam(model.getLogo());
        i.setType(2);
        i.setHeader(3);
        i.setWidth(97);
        i.setHigh(97);
        i.setXAxis(148);
        i.setYAxis(190);
        list.add(i);

        ImageEntity i2 = new ImageEntity();
        i2.setParam(model.getName());
        i2.setType(1);
        i2.setSize(40);
        i2.setColor(new Color(0,0,0));
        i2.setXAxis(366);
        i2.setYAxis(177);
        i2.setPlain(Font.BOLD);
        list.add(i2);

        if(!StringUtils.isEmpty(model.getPosition())){
            ImageEntity post = new ImageEntity();
            post.setParam(model.getPosition());
            post.setType(1);
            post.setSize(24);
            post.setColor(new Color(0,0,0));
            post.setXAxis(362);
            post.setYAxis(230);
            list.add(post);
        }

        ImageEntity i3 = new ImageEntity();
        i3.setParam(model.getPhone());
        i3.setType(1);
        i3.setSize(24);
        i3.setColor(new Color(0,0,0));
        i3.setXAxis(400);
        i3.setYAxis(285);
        i3.setPlain(Font.PLAIN);
        list.add(i3);

        ImageEntity i4 = new ImageEntity();
        i4.setParam(model.getEmail());
        i4.setType(1);
        i4.setSize(24);
        i4.setColor(new Color(0,0,0));
        i4.setXAxis(400);
        i4.setYAxis(326);
        i4.setPlain(Font.PLAIN);
        list.add(i4);

        ImageEntity i5 = new ImageEntity();
        i5.setParam(model.getWxTwoCode());
        i5.setType(2);
        i5.setWidth(401);
        i5.setHigh(401);
        i5.setXAxis(159);
        i5.setYAxis(636);
        list.add(i5);

        imageEntity.setImageEntityList(list);
        InputStream inputStream = imageGenerateUtil.image(imageEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        log.info("url------->:{}",url);
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Async("asyncServiceExecutor")
    public String card8(BusinessCardModel model) {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setParam(cardPosterConfig.getUrl8());
        List<ImageEntity> list = new ArrayList<>();
        ImageEntity com = new ImageEntity();
        com.setParam(model.getCompanyName());
        com.setType(1);
        com.setSize(30);
        com.setColor(new Color(13,53,104));
        com.setXAxis(31);
        com.setYAxis(181);
        list.add(com);

        ImageEntity i2 = new ImageEntity();
        i2.setParam(model.getName().length() > 6 ? model.getName().substring(0,6) : model.getName());
        i2.setType(1);
        i2.setSize(60);
        i2.setColor(new Color(13,53,104));
        i2.setXAxis(82);
        i2.setYAxis(445);
        i2.setPlain(Font.BOLD);
        list.add(i2);

        if(!StringUtils.isEmpty(model.getPosition())){
            ImageEntity post = new ImageEntity();
            post.setParam(model.getPosition());
            post.setType(1);
            post.setSize(24);
            post.setColor(new Color(13,53,104));
            post.setXAxis(249);
            post.setYAxis(445);
            list.add(post);
        }

        ImageEntity i3 = new ImageEntity();
        i3.setParam(model.getPhone());
        i3.setType(1);
        i3.setSize(24);
        i3.setColor(new Color(13,53,104));
        i3.setXAxis(289);
        i3.setYAxis(500);
        i3.setPlain(Font.PLAIN);
        list.add(i3);

        ImageEntity i4 = new ImageEntity();
        i4.setParam(model.getEmail());
        i4.setType(1);
        i4.setSize(24);
        i4.setColor(new Color(13,53,104));
        i4.setXAxis(289);
        i4.setYAxis(540);
        i4.setPlain(Font.PLAIN);
        list.add(i4);

        ImageEntity i5 = new ImageEntity();
        i5.setParam(model.getWxTwoCode());
        i5.setType(2);
        i5.setWidth(401);
        i5.setHigh(401);
        i5.setXAxis(67);
        i5.setYAxis(743);
        list.add(i5);


        imageEntity.setImageEntityList(list);
        InputStream inputStream = imageGenerateUtil.image(imageEntity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");
        addCardList(url, model.getCardId());
        return url;
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public String getWxCode(String cardId, String companyId) {
        if (StringUtils.isBlank(cardId)) {
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer("card=").append(cardId).append("&c=").append(companyId);
        Map<String, String> map = new HashMap<>(2);
        map.put("scene", stringBuffer.toString());
        map.put("page", cardSunCode);
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(map));
        CompanyAccountModel companyAccountModel = companyAccontService.selectByUserIdCopy(new CompanyAccountRequest() {{
            setCompanyId(Integer.parseInt(companyId));
            setAccountType(LoginEnum.USER.getAccountType());
        }});
        if (companyAccountModel != null) {
            String twoCode = wxSunCodeService.getWxCode(jsonObject, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
            log.info("获取到太阳码：{}", twoCode);
            if (StringUtils.isNotBlank(twoCode)) {
                businessCardMapper.updateByPrimaryKeySelective(new BusinessCardModel() {{
                    setCardId(Integer.parseInt(cardId));
                    setWxTwoCode(twoCode);
                }});
                return twoCode;
            }
        }
        return null;
    }

    @Override
    public ResultModel getDynamicPoster(ShareRecordRequest request) {
        log.info("获取文章海报: {}", JSON.toJSONString(request));
        ShareRecordModel shareRecordModel = shareRecordMapper.selectByShardRecordId(request.getShardRecordId());
        if(shareRecordModel == null){
            log.error("未获取到文章分享记录");
            return ResultModel.fail("未获取到文章分享记录:" + request.getShardRecordId());

        }
        DynamicModel model = dynamicMapper.selectByPrimaryKey(shareRecordModel.getItemId());
        if (null == model) {
            log.error("未获取到文章信息，当前分享记录为:{}", JSON.toJSONString(shareRecordModel));
            return ResultModel.fail("未获取到文章信息");
        }

        // 从商品的company_id 查找company表中user_id，然后再查找user表中user_id对应数据的enterprise_id，最终确定真正小程序的company_id
        Integer companyId = companyMapper.selectEnterpriseIdByCompanyId(model.getCompanyId());
        CompanyAccountModel companyAccountModel= companyAccontService.selectByCompanyKeyDefault(new CompanyAccountRequest(){{
            setCompanyId(companyId);
        }}) ;

        StringBuffer stringBuffer = new StringBuffer();
        //名片id
        stringBuffer.append("card=").append(businessCardMapper.getBoosCardId(model.getCompanyId()));
        //公司id
        stringBuffer.append("&c=").append(model.getCompanyId());
        // 分享记录id
        stringBuffer.append("&shareId=").append(request.getShardRecordId());
        // 文章id
        stringBuffer.append("&dynamic=").append(model.getDynamicId());
        // 类型为1为分享的文章海报
        stringBuffer.append("&type=1");
        // scene 的长度不能超过32

        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", stringBuffer);
        paramJson.put("page", dynamicSunCode);
        log.info("动态太阳码参数：{}", paramJson.toJSONString());
        log.info("企业账号信息：{}", JSON.toJSONString(companyAccountModel));
//        String sunCodeUrl = wxSunCodeService.getWxCode(paramJson, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
        String sunCodeUrl = wxSunCodeService.getWxCodeScene(paramJson, companyAccountModel.getAppId(), companyAccountModel.getAppSecret());
        log.info("动态太阳码地址：{}", sunCodeUrl);
        DynamicPosterEntity entity = new DynamicPosterEntity();
        entity.setTitle(model.getTitle());
        entity.setDynamicPhoto(model.getPhotos());

        entity.setWxTwoCode(sunCodeUrl);
        entity.setAppName(companyAccountModel.getAppName());
        UserModel user = userMapper.selectByPrimaryKey(request.getId().intValue());
        entity.setNickeName(new String(Base64.decode(user.getNickeName())));
        entity.setAvatarUrl(user.getAvatarUrl());
//        InputStream inputStream = imageGenerateUtil.getDynamicPosterDraw(entity);
//        InputStream inputStream = imageGenerateUtil.getDynamicPosterDraw(entity);

        InputStream inputStream = imageGenerateUtil.getDynamicPosterDraw2(entity);
        String url = ossUtil.getOssUrl() + ossUtil.uploadObjectOSS(inputStream, "png");

        return ResultModel.success(url);
    }

}
